package ruletree;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import managers.ComponentManager;
import managers.SemanticsManager;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import components.Component;
import components.Leaf;
import components.Phrase;

import ruletree.rule.Rule;

public class Folder extends RuleTree {

	public static final String NAME = "name";
	


	public Folder(Element node) {
		super(node);	
	}

	public static Folder createInstance(Element rootNode) {
		
		//String treeDirectory = "Languages\\Filipino\\RuleTree\\";
	
		Folder folder = new Folder(rootNode);
		List<Element> children = rootNode.getChildren();
		
		for (Element child : children) {
			if (child.getName().equals("folder")) {
				//System.out.println(child + " in folder");
				folder.addFolder(Folder.createInstance(child));
			} else if(child.getName().equalsIgnoreCase("rules")) {
				//System.out.println(child + " in folder rules");
				SAXBuilder builder = new SAXBuilder();
				String dir = rootNode.getAttributeValue("name") + "\\" + child.getAttributeValue("name") + ".xml";
				//System.out.println("dir is " + dir);
				File file = new File(dir);
				try {	
					Document doc = builder.build(file);
					Element node = doc.getRootElement();
					//System.out.println(node.getAttributeValue("name"));
					folder.addRule(Rule.createInstance(node));
				} catch (Exception e) {
				}
			}
		}
		return folder;
	}
	
	public Element generateXMLFolder(){
		
		System.out.println("entered generateXMLFolder");
		
		Element xmlElement = new Element("folder");
		xmlElement.setAttribute("name", super.getName());
		
		if(folderList!= null){
			System.out.println("folderChildren is not null");
			for(Folder folder : folderList )
				xmlElement.addContent(folder.generateXMLFolder());
		}
		
		if(ruleList != null){
			for(Rule rule : ruleList){
				System.out.println("ruleList is not null");
				//xmlElement.addContent(rule.generateXMLRule());
			}
		}
	
		return xmlElement;

	}

}
